﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using ProcessBase.Models;
using SubstrateHelper.Data;

namespace SubstrateHelper.Helpers
{
    public class ProcessRecordSaveHelper
    {

        public static string Save(List<ProcessDetail> details)
        {
            
            string re = "";
            using (var scope = Global.Host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                try
                {
                    string guid = details[0].Record.Guid;
                    var Db = services.GetRequiredService<SubstrateHelperDbContext>();
                    
                    foreach(var detail in details)
                    {
                        var record = detail.Record;
                        var recordInDb=Db.Records.Where(x => x.Guid == record.Guid && x.ProcessName == record.ProcessName && x.ParameterName == record.ParameterName).FirstOrDefault();

                        if(recordInDb==null)//没有该项记录
                        {
                            Db.Records.Add(record);
                        }
                        else
                        {
                            recordInDb.Date = record.Date;
                            recordInDb.StringValue = record.StringValue;
                            recordInDb.NumberValue = record.NumberValue;
                            recordInDb.DateTimeValue = record.DateTimeValue;
                            recordInDb.CheckResult = record.CheckResult;
                            recordInDb.Inspector = record.Inspector;
                            recordInDb.QualityState = record.QualityState;                            
                        }
                    }
                    
                    Db.SaveChanges();

                    var st=Helpers.ProcessStatisticsHelper.MakeStatistics(guid);
                    if (st != null)
                    {
                        var stInDb=Db.ProcessStatistics.Where(x => x.Guid == guid).FirstOrDefault();
                        if (stInDb == null)//数据库未有该记录
                        {
                            Db.ProcessStatistics.Add(st);
                        }
                        else
                        {
                            stInDb.CopyFrom(st);
                                           
                        }
                        Db.SaveChanges();
                    }

                    

                }
                catch (Exception ex)
                {
                    re = ex.Message;
                    var logger = services.GetRequiredService<ILogger<Program>>();
                    logger.LogError(ex, "MakeStatistics");
                    
                }
            }
            return re;
        }
    }
}
